﻿using CommonUtils;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using WebSocketSharp;

namespace Test.Core.Web.apis
{
    [Route("api/[controller]/[action]")]
    public class WebSocketServerController : ControllerBase
    {
        private static Queue<string> _logs = new Queue<string>();

        private void Server_OnError(Exception obj)
        {
            _logs.Enqueue("Server error: " + obj.Message);
        }
        private void Server_OnStart()
        {
            _logs.Enqueue("Server startted!");
        }

        private void Server_OnSendMessage(string arg1, WebSocketServerSession arg2)
        {
            _logs.Enqueue("Server sended message:\r\n" + arg1 + "\r\nto " + arg2.ClientEndPoint);
        }

        private void Server_OnStop()
        {
            _logs.Enqueue("Server stopped!");
        }

        private void Server_OnSessionError(Exception arg1, WebSocketServerSession arg2)
        {
            _logs.Enqueue("Session error: " + arg1.Message + "\r\non " + arg2.ClientEndPoint);
        }

        private void Server_OnSessionConnect(WebSocketServerSession obj)
        {
            _logs.Enqueue("Session connect: " + obj.ClientEndPoint);
        }

        private void Server_OnSessionReceiveMessage(MessageEventArgs arg1, WebSocketServerSession arg2)
        {
            _logs.Enqueue("Receive message:\r\n" + arg1.Data);
        }

        private void Server_OnSessionDisconnect(WebSocketServerSession obj)
        {
            _logs.Enqueue("Session disconnect: " + obj.ClientEndPoint);
        }

        private static WebSocketServer _server;

        [HttpPost]
        public ApiResult Startup(int port, string route)
        {
            if (_server != null)
                _server.Stop();
            _server = new WebSocketServer(port, route);
            _server.OnError += Server_OnError;
            _server.OnStart += Server_OnStart;
            _server.OnSendMessage += Server_OnSendMessage;
            _server.OnStop += Server_OnStop;
            _server.OnSessionError += Server_OnSessionError;
            _server.OnSessionConnect += Server_OnSessionConnect;
            _server.OnSessionReceiveMessage += Server_OnSessionReceiveMessage;
            _server.OnSessionDisconnect += Server_OnSessionDisconnect;
            _server.Start();
            return ApiResult.Ok("Server start!");
        }

        [HttpPost]
        public ApiResult Stop()
        {
            _server.Stop();
            return ApiResult.Ok("Server stop!");
        }

        private const string _msgKey = "WebSocketServer.Msg";

        [HttpPost]
        public ApiResult Send()
        {
            var msg = Request.GetBodyText();
            _server.Send(msg);
            CacheUtil.SetWithFile(_msgKey, msg);
            return ApiResult.Ok("Server send message:\r\n" + msg);
        }

        [HttpPost]
        public ApiResult GetLog()
        {
            if (_logs.Count > 0)
                return ApiResult.Ok(_logs.Dequeue());
            else
                return ApiResult.Ok();
        }

        [HttpPost]
        public ApiResult GetMsgCache()
        {
            if (CacheUtil.ContainsInFiles(_msgKey, out string value))
                return ApiResult.Ok(value);
            else
                return ApiResult.Ok();
        }

        [HttpPost]
        public ApiResult GetState()
        {
            if (_server == null)
                return ApiResult.Ok("服务未启动,请点击按钮启动监听");
            else
                return ApiResult.Ok(_server.Status);
        }
    }
}